const Koa = require('koa');
const views = require('koa-views');
const koaStatic = require('koa-static');
const Router = require('koa-router');
const path = require('path');

const router = new Router();

router.get('/', async (ctx) => {
  await ctx.render('index');
});
router.get('/detail/*', async (ctx) => {
  await ctx.render('index');
});

const app = new Koa();

// x-response-time
app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
});

// logger
app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});

// template
app.use(views(path.join(__dirname, './views'), {
  extension: 'html',
}));

app.use(koaStatic(`${__dirname}`));

app.use(router.routes())
  .use(router.allowedMethods());

app.listen(9001);
console.log(`listening on port ${9001}`);
